/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo.dao;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import modelo.Sgpais;
import modelo.Sgmunicipio;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import modelo.Sguf;
import modelo.SgufPK;
import modelo.dao.exceptions.IllegalOrphanException;
import modelo.dao.exceptions.NonexistentEntityException;
import modelo.dao.exceptions.PreexistingEntityException;

/**
 *
 * @author Marcio
 */
public class SgufJpaController implements Serializable {

    public SgufJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Sguf sguf) throws PreexistingEntityException, Exception {
        if (sguf.getSgufPK() == null) {
            sguf.setSgufPK(new SgufPK());
        }
        if (sguf.getSgmunicipioCollection() == null) {
            sguf.setSgmunicipioCollection(new ArrayList<Sgmunicipio>());
        }
        sguf.getSgufPK().setCodpais(sguf.getSgpais().getCodpais());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sgpais sgpais = sguf.getSgpais();
            if (sgpais != null) {
                sgpais = em.getReference(sgpais.getClass(), sgpais.getCodpais());
                sguf.setSgpais(sgpais);
            }
            Collection<Sgmunicipio> attachedSgmunicipioCollection = new ArrayList<Sgmunicipio>();
            for (Sgmunicipio sgmunicipioCollectionSgmunicipioToAttach : sguf.getSgmunicipioCollection()) {
                sgmunicipioCollectionSgmunicipioToAttach = em.getReference(sgmunicipioCollectionSgmunicipioToAttach.getClass(), sgmunicipioCollectionSgmunicipioToAttach.getSgmunicipioPK());
                attachedSgmunicipioCollection.add(sgmunicipioCollectionSgmunicipioToAttach);
            }
            sguf.setSgmunicipioCollection(attachedSgmunicipioCollection);
            em.persist(sguf);
            if (sgpais != null) {
                sgpais.getSgufCollection().add(sguf);
                sgpais = em.merge(sgpais);
            }
            for (Sgmunicipio sgmunicipioCollectionSgmunicipio : sguf.getSgmunicipioCollection()) {
                Sguf oldSgufOfSgmunicipioCollectionSgmunicipio = sgmunicipioCollectionSgmunicipio.getSguf();
                sgmunicipioCollectionSgmunicipio.setSguf(sguf);
                sgmunicipioCollectionSgmunicipio = em.merge(sgmunicipioCollectionSgmunicipio);
                if (oldSgufOfSgmunicipioCollectionSgmunicipio != null) {
                    oldSgufOfSgmunicipioCollectionSgmunicipio.getSgmunicipioCollection().remove(sgmunicipioCollectionSgmunicipio);
                    oldSgufOfSgmunicipioCollectionSgmunicipio = em.merge(oldSgufOfSgmunicipioCollectionSgmunicipio);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findSguf(sguf.getSgufPK()) != null) {
                throw new PreexistingEntityException("Sguf " + sguf + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Sguf sguf) throws IllegalOrphanException, NonexistentEntityException, Exception {
        sguf.getSgufPK().setCodpais(sguf.getSgpais().getCodpais());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sguf persistentSguf = em.find(Sguf.class, sguf.getSgufPK());
            Sgpais sgpaisOld = persistentSguf.getSgpais();
            Sgpais sgpaisNew = sguf.getSgpais();
            Collection<Sgmunicipio> sgmunicipioCollectionOld = persistentSguf.getSgmunicipioCollection();
            Collection<Sgmunicipio> sgmunicipioCollectionNew = sguf.getSgmunicipioCollection();
            List<String> illegalOrphanMessages = null;
            for (Sgmunicipio sgmunicipioCollectionOldSgmunicipio : sgmunicipioCollectionOld) {
                if (!sgmunicipioCollectionNew.contains(sgmunicipioCollectionOldSgmunicipio)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Sgmunicipio " + sgmunicipioCollectionOldSgmunicipio + " since its sguf field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (sgpaisNew != null) {
                sgpaisNew = em.getReference(sgpaisNew.getClass(), sgpaisNew.getCodpais());
                sguf.setSgpais(sgpaisNew);
            }
            Collection<Sgmunicipio> attachedSgmunicipioCollectionNew = new ArrayList<Sgmunicipio>();
            for (Sgmunicipio sgmunicipioCollectionNewSgmunicipioToAttach : sgmunicipioCollectionNew) {
                sgmunicipioCollectionNewSgmunicipioToAttach = em.getReference(sgmunicipioCollectionNewSgmunicipioToAttach.getClass(), sgmunicipioCollectionNewSgmunicipioToAttach.getSgmunicipioPK());
                attachedSgmunicipioCollectionNew.add(sgmunicipioCollectionNewSgmunicipioToAttach);
            }
            sgmunicipioCollectionNew = attachedSgmunicipioCollectionNew;
            sguf.setSgmunicipioCollection(sgmunicipioCollectionNew);
            sguf = em.merge(sguf);
            if (sgpaisOld != null && !sgpaisOld.equals(sgpaisNew)) {
                sgpaisOld.getSgufCollection().remove(sguf);
                sgpaisOld = em.merge(sgpaisOld);
            }
            if (sgpaisNew != null && !sgpaisNew.equals(sgpaisOld)) {
                sgpaisNew.getSgufCollection().add(sguf);
                sgpaisNew = em.merge(sgpaisNew);
            }
            for (Sgmunicipio sgmunicipioCollectionNewSgmunicipio : sgmunicipioCollectionNew) {
                if (!sgmunicipioCollectionOld.contains(sgmunicipioCollectionNewSgmunicipio)) {
                    Sguf oldSgufOfSgmunicipioCollectionNewSgmunicipio = sgmunicipioCollectionNewSgmunicipio.getSguf();
                    sgmunicipioCollectionNewSgmunicipio.setSguf(sguf);
                    sgmunicipioCollectionNewSgmunicipio = em.merge(sgmunicipioCollectionNewSgmunicipio);
                    if (oldSgufOfSgmunicipioCollectionNewSgmunicipio != null && !oldSgufOfSgmunicipioCollectionNewSgmunicipio.equals(sguf)) {
                        oldSgufOfSgmunicipioCollectionNewSgmunicipio.getSgmunicipioCollection().remove(sgmunicipioCollectionNewSgmunicipio);
                        oldSgufOfSgmunicipioCollectionNewSgmunicipio = em.merge(oldSgufOfSgmunicipioCollectionNewSgmunicipio);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                SgufPK id = sguf.getSgufPK();
                if (findSguf(id) == null) {
                    throw new NonexistentEntityException("The sguf with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(SgufPK id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sguf sguf;
            try {
                sguf = em.getReference(Sguf.class, id);
                sguf.getSgufPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The sguf with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Sgmunicipio> sgmunicipioCollectionOrphanCheck = sguf.getSgmunicipioCollection();
            for (Sgmunicipio sgmunicipioCollectionOrphanCheckSgmunicipio : sgmunicipioCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Sguf (" + sguf + ") cannot be destroyed since the Sgmunicipio " + sgmunicipioCollectionOrphanCheckSgmunicipio + " in its sgmunicipioCollection field has a non-nullable sguf field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Sgpais sgpais = sguf.getSgpais();
            if (sgpais != null) {
                sgpais.getSgufCollection().remove(sguf);
                sgpais = em.merge(sgpais);
            }
            em.remove(sguf);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Sguf> findSgufEntities() {
        return findSgufEntities(true, -1, -1);
    }

    public List<Sguf> findSgufEntities(int maxResults, int firstResult) {
        return findSgufEntities(false, maxResults, firstResult);
    }

    private List<Sguf> findSgufEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Sguf.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Sguf findSguf(SgufPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Sguf.class, id);
        } finally {
            em.close();
        }
    }

    public int getSgufCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Sguf> rt = cq.from(Sguf.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
    public List<Sguf> getUfByNomeUf(String nomeUf) {
        EntityManager em = getEntityManager();
        if (nomeUf == null || nomeUf.isEmpty()) {
            return null;
        }
        List<Sguf> uf = null;
        //nome = "%" +nome.trim() +"%";
        try {
            uf = em.createNamedQuery("Sguf.findByNomeUf").setParameter("nomeuf", nomeUf).getResultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uf;
    }
    
    public Sguf getUfByNomeUfSingle(String nomeUf) {
        EntityManager em = getEntityManager();
        if (nomeUf == null || nomeUf.isEmpty()) {
            return null;
        }
        Sguf uf = null;
        //nome = "%" +nome.trim() +"%";
        try {
            uf = (Sguf) em.createNamedQuery("Sguf.findByNomeUf").setParameter("nomeuf", nomeUf).getSingleResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uf;
    }
    
}
